//
//  DR_ResultVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/18.
//

import UIKit
import SnapKit

class DR_ResultVC: DR_BaseVC {
    
    private let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        return scrollView
    }()
    
    private let contentView = UIView()
    private let successView = DR_ResultSucceccView()
    private let editView = DR_ResultEditView()
    
    private var pdfModel: DR_PDFFileModel?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
    }
    
    // MARK: - Public Methods
    
    func configure(with pdfModel: DR_PDFFileModel, operationType: DR_ResultSucceccView.OperationType = .merge) {
        self.pdfModel = pdfModel
        
        // 格式化日期
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateString = dateFormatter.string(from: pdfModel.createDate)
        
        // 获取文件路径（简化显示）
        let filePath = pdfModel.fileURL.path
        
        // 异步加载缩略图
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let thumbnail = DR_PDFTool.shared.getPDFThumbnail(fileURL: pdfModel.fileURL, size: CGSize(width: 86, height: 120))
            
            DispatchQueue.main.async {
                self?.successView.configure(
                    fileName: pdfModel.fileName,
                    date: dateString,
                    size: pdfModel.fileSizeString,
                    filePath: filePath,
                    thumbnail: thumbnail,
                    operationType: operationType
                )
            }
        }
    }

    private func setupUI(){
        view.backgroundColor = .white
        
        view.addSubview(backButton)
        view.addSubview(homeButton)
        
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(successView)
        contentView.addSubview(editView)
        
        // 设置按钮事件
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        homeButton.addTarget(self, action: #selector(homeButtonTapped), for: .touchUpInside)
        
        // 设置图片选择回调
        editView.onImagesSelected = { [weak self] images in
            self?.handleImagesSelected(images)
        }
        
        editView.functionBlock = { [weak self] idx in
            self?.handleFunctionTapped(idx: idx)
        }
        
        // 设置回调
        successView.onOpenTapped = { [weak self] in
            self?.handleOpenTapped()
        }
        
        successView.onShareTapped = { [weak self] in
            self?.handleShareTapped()
        }
    }
    
    private func setupConstraints(){
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.height.equalTo(44)
        }

        homeButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalTo(backButton)
            make.width.height.equalTo(30)
        }
        
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom).offset(5)
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        successView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(281)
        }
        
        editView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(successView.snp.bottom)
            make.bottom.equalToSuperview()
            make.height.equalTo(355)
        }
    }
    
    private let backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("choose_close".toImage, for: .normal)
        return v
    }()
    
    private let homeButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("result_home".toImage, for: .normal)
        return v
    }()
    
    // MARK: - Actions
    
    @objc private func backButtonTapped() {
        if let navController = navigationController {
            navController.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
    }
    
    @objc private func homeButtonTapped() {
        // 找到 TabBarController 并切换到首页
        if let window = UIApplication.shared.keyWindowCompat,
           let rootVC = window.rootViewController {
            let tabBarController = findTabBarController(from: rootVC)
            
            // 切换到首页 tab
            tabBarController?.selectedIndex = 0
            
            // 如果首页有导航控制器，pop 到根视图控制器
            if let navController = tabBarController?.selectedViewController as? UINavigationController {
                navController.popToRootViewController(animated: false)
            }
        }
        
        // 关闭当前页面
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
            if let navController = self?.navigationController {
                // 如果在导航栈中，pop 当前页面
                navController.popViewController(animated: true)
            } else {
                // 如果是 presented 的，dismiss
                self?.dismiss(animated: true)
            }
        }
    }
    
    private func findTabBarController(from viewController: UIViewController) -> UITabBarController? {
        if let tabBarController = viewController as? UITabBarController {
            return tabBarController
        }
        
        if let navController = viewController as? UINavigationController,
           let topVC = navController.topViewController {
            return findTabBarController(from: topVC)
        }
        
        if let presentedVC = viewController.presentedViewController {
            return findTabBarController(from: presentedVC)
        }
        
        return nil
    }
    
    // MARK: - 处理选中的图片
    private func handleImagesSelected(_ images: [UIImage]) {
        print("选中了 \(images.count) 张图片")
        
        // 显示加载提示
        view.makeToastActivity(.center)
        
        // 在后台线程处理 PDF 生成
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            // 生成 PDF
            guard let pdfModel = DR_PDFTool.shared.createPDF(from: images) else {
                DispatchQueue.main.async {
                    self?.view.hideToastActivity()
                    self?.view.makeToast("pdr_generaF".localized, duration: 2.0, position: .center)
                }
                return
            }
            
            // 回到主线程显示结果并跳转到预览页面
            DispatchQueue.main.async {
                self?.view.hideToastActivity()
                print("✅ PDF 已保存: \(pdfModel.fileURL.path)")
                
                // 跳转到预览页面
                let previewVC = DR_LookPDFVC()
                previewVC.configure(with: pdfModel)
                self?.pushHidingTabBar(previewVC, animated: true)
            }
        }
    }
    
    private func handleFunctionTapped(idx: Int) {
        // 在导航栈中查找 DR_SelectVC
        if let navController = navigationController {
            // 遍历导航栈，查找 DR_SelectVC
            for viewController in navController.viewControllers {
                if let selectVC = viewController as? DR_SelectVC {
                    // 找到 DR_SelectVC，设置 type 并 pop 到它
                    selectVC.type = idx
                    navController.popToViewController(selectVC, animated: true)
                    return
                }
            }
        }
        
        // 如果没有找到 DR_SelectVC，创建新的并 push
        let selVC = DR_SelectVC()
        selVC.type = idx
        pushHidingTabBar(selVC, animated: true)
    }
    
    private func handleOpenTapped() {
        guard let pdfModel = pdfModel else { return }
        
        // 打开PDF预览页面
        let previewVC = DR_LookPDFVC()
        previewVC.configure(with: pdfModel)
        pushHidingTabBar(previewVC, animated: true)
    }
    
    private func handleShareTapped() {
        guard let pdfModel = pdfModel else { return }
        
        // 分享PDF文件
        let activityVC = UIActivityViewController(activityItems: [pdfModel.fileURL], applicationActivities: nil)
        
        // 适配iPad
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityVC, animated: true)
    }
}
